/**
 * 表格管理通用逻辑 Hook
 *
 * 抽取表格组件的通用业务逻辑
 * 包括分页、排序、筛选、选择等功能
 */

import { ref, reactive, computed, watch, onMounted, onBeforeUnmount, type Ref } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";

// 🔧 基础类型定义
interface WmsTableColumn<T = any> {
  prop: string;
  label: string;
  width?: string | number;
  fixed?: boolean | 'left' | 'right';
  sortable?: boolean;
  visible?: boolean;
  formatter?: (row: T, column: any, cellValue: any) => string;
  render?: (row: T) => any;
}

interface WmsTableConfig {
  stripe?: boolean;
  border?: boolean;
  size?: 'large' | 'default' | 'small';
  height?: string | number;
  maxHeight?: string | number;
}

interface WmsPaginationConfig {
  page: number;
  limit: number;
  total: number;
  pageSizes?: number[];
  layout?: string;
  background?: boolean;
  small?: boolean;
  autoScroll?: boolean;
}

/**
 * 表格配置接口
 */
interface UseTableOptions<T = any> {
  /** 获取数据的API函数 */
  fetchApi?: (params: any) => Promise<{ data?: T[]; rows?: T[]; total: number }>;
  /** 初始查询参数 */
  initialQuery?: Record<string, any>;
  /** 初始分页配置 */
  initialPagination?: Partial<WmsPaginationConfig>;
  /** 是否立即加载数据 */
  immediate?: boolean;
  /** 是否保持查询参数到URL */
  keepQueryInUrl?: boolean;
  /** 核心配置 (art-design-pro 风格) */
  core?: {
    apiFn?: (params: any) => Promise<{ data?: T[]; rows?: T[]; total: number }>;
    apiParams?: Record<string, any>;
    columnsFactory?: () => WmsTableColumn<T>[];
  };
}

/**
 * 表格管理Hook返回值
 */
interface UseTableReturn<T = any> {
  // 数据状态
  data: Ref<T[]>;
  tableData: Ref<T[]>; // 🔧 添加 tableData 别名以兼容现有组件
  loading: Ref<boolean>;
  isLoading: Ref<boolean>; // 🔧 添加 isLoading 别名以兼容现有组件
  total: Ref<number>;

  // 分页状态
  pagination: Ref<WmsPaginationConfig>;
  paginationState: Ref<WmsPaginationConfig>; // 🔧 添加 paginationState 别名以兼容现有组件

  // 查询状态
  query: Ref<Record<string, any>>;
  searchFilter: Ref<Record<string, any>>; // 🔧 添加 searchFilter 别名以兼容现有组件

  // 选择状态
  selectedRows: Ref<T[]>;
  selectedRowKeys: Ref<any[]>;

  // 排序状态
  sortField: Ref<string | null>;
  sortOrder: Ref<"ascending" | "descending" | null>;

  // 表格列配置
  columns: Ref<WmsTableColumn<T>[]>; // 🔧 添加 columns 以兼容现有组件
  columnChecks: Ref<Record<string, boolean>>; // 🔧 添加 columnChecks 以兼容现有组件

  // 方法
  loadData: () => Promise<void>;
  refresh: () => Promise<void>;
  refreshData: () => Promise<void>; // 🔧 添加 refreshData 别名以兼容现有组件
  search: (newQuery?: Record<string, any>) => Promise<void>;
  handleSearch: (newQuery?: Record<string, any>) => Promise<void>; // 🔧 添加 handleSearch 别名以兼容现有组件
  resetQuery: () => Promise<void>;
  handleReset: () => Promise<void>; // 🔧 添加 handleReset 别名以兼容现有组件
  handlePageChange: (page: number, pageSize: number) => void;
  onPageSizeChange: (page: number, pageSize: number) => void; // 🔧 添加 onPageSizeChange 别名以兼容现有组件
  onCurrentPageChange: (page: number, pageSize: number) => void; // 🔧 添加 onCurrentPageChange 别名以兼容现有组件
  handleSortChange: (field: string, order: string | null) => void;
  handleSelectionChange: (selection: T[]) => void;
  clearSelection: () => void;
  toggleRowSelection: (row: T, selected?: boolean) => void;
  setQuery: (newQuery: Record<string, any>) => void;
  setPagination: (newPagination: Partial<WmsPaginationConfig>) => void;
}

/**
 * 表格管理通用Hook
 */
export function useTable<T = any>(
  options: UseTableOptions<T> = {},
): UseTableReturn<T> {
  const {
    fetchApi,
    initialQuery = {},
    initialPagination = {},
    immediate = true,
    keepQueryInUrl = false,
    core,
  } = options;

  // 数据状态
  const data = ref<T[]>([]) as Ref<T[]>;
  const loading = ref(false);
  const total = ref(0);

  // 表格列配置
  const columns = ref<WmsTableColumn<T>[]>(core?.columnsFactory?.() || []);
  const columnChecks = ref<Record<string, boolean>>({});

  // 分页状态
  const pagination = ref<WmsPaginationConfig>({
    page: 1,
    limit: 20,
    total: 0,
    pageSizes: [10, 20, 30, 50],
    layout: "total, sizes, prev, pager, next, jumper",
    background: true,
    small: false,
    autoScroll: true,
    ...initialPagination,
  });

  // 查询状态
  const query = ref<Record<string, any>>({ ...initialQuery });

  // 选择状态
  const selectedRows = ref<T[]>([]) as Ref<T[]>;
  const selectedRowKeys = ref<any[]>([]);

  // 排序状态
  const sortField = ref<string | null>(null);
  const sortOrder = ref<"ascending" | "descending" | null>(null);

  /**
   * 加载数据
   */
  const loadData = async (): Promise<void> => {
    // 🔧 支持 core 配置或传统 fetchApi
    const apiFunction = core?.apiFn || fetchApi;
    if (!apiFunction) return;

    try {
      loading.value = true;

      // 🔧 安全处理分页参数，确保不传递null值
      const safeParams = {
        ...(core?.apiParams || {}),
        ...query.value,
        current: pagination.value.page || 1,
        size: pagination.value.limit || 20,
        pageNum: pagination.value.page || 1, // 兼容旧格式
        pageSize: pagination.value.limit || 20, // 兼容旧格式
        ...(sortField.value && {
          orderBy: sortField.value,
          orderDirection: sortOrder.value === "ascending" ? "asc" : "desc",
        }),
      };

      // 🧹 清理null/undefined值，防止后端解析错误 - 增强版
      const params = Object.fromEntries(
        Object.entries(safeParams).filter(([key, value]) => {
          const isValid = value !== null && 
                         value !== undefined && 
                         value !== "" && 
                         value !== "null" &&
                         String(value) !== "null" &&
                         !(typeof value === 'string' && value.toLowerCase() === 'null');
          
          if (!isValid) {
            console.warn(`[useTable] ⚠️ 过滤无效参数: ${key} = ${value} (${typeof value})`);
          }
          
          return isValid;
        })
      );

      console.log(`[useTable] 📤 发送请求参数:`, params);

      const response = await apiFunction(params);

      console.log(`[useTable] 📥 接收到响应:`, {
        response: response,
        responseType: typeof response,
        hasRows: !!(response && response.rows),
        hasData: !!(response && response.data), 
        hasTotal: !!(response && response.total),
        rowsLength: response?.rows?.length || 0,
        dataLength: response?.data?.length || 0
      });

      // 🛡️ 响应安全检查（双重保障）
      if (!response || typeof response !== 'object') {
        console.warn('[useTable] ⚠️ 响应无效，使用默认数据');
        data.value = [];
        total.value = 0;
        pagination.value.total = 0;
        return;
      }

      // 🔧 RuoYi标准格式处理（request.ts已标准化）
      data.value = response.rows || response.data || [];
      total.value = response.total || (response as any).count || 0;
      pagination.value.total = total.value;

      console.log(`[useTable] ✅ 数据解析完成: ${data.value.length} 条记录, 总数: ${total.value}`);
    } catch (error) {
      console.error("[useTable] 💥 数据加载失败:", error);
      // request.ts已处理错误提示，这里只重置UI状态
      data.value = [];
      total.value = 0;
      pagination.value.total = 0;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 刷新数据
   */
  const refresh = async (): Promise<void> => {
    await loadData();
  };

  /**
   * 搜索数据
   */
  const search = async (newQuery?: Record<string, any>): Promise<void> => {
    if (newQuery) {
      query.value = { ...query.value, ...newQuery };
    }

    // 搜索时重置到第一页
    pagination.value.page = 1;

    await loadData();
  };

  /**
   * 重置查询条件
   */
  const resetQuery = async (): Promise<void> => {
    query.value = { ...initialQuery };
    pagination.value.page = 1;
    sortField.value = null;
    sortOrder.value = null;

    await loadData();
  };

  /**
   * 处理分页变化
   */
  const handlePageChange = (page: number, pageSize: number): void => {
    pagination.value.page = page;
    pagination.value.limit = pageSize;
    loadData();
  };

  /**
   * 处理排序变化
   */
  const handleSortChange = (field: string, order: string | null): void => {
    sortField.value = field;
    sortOrder.value = order as "ascending" | "descending" | null;
    pagination.value.page = 1; // 排序时重置到第一页
    loadData();
  };

  /**
   * 处理选择变化
   */
  const handleSelectionChange = (selection: T[]): void => {
    selectedRows.value = selection;
    selectedRowKeys.value = selection.map((row: any) => row.id || row.key);
  };

  /**
   * 清空选择
   */
  const clearSelection = (): void => {
    selectedRows.value = [];
    selectedRowKeys.value = [];
  };

  /**
   * 切换行选择状态
   */
  const toggleRowSelection = (row: T, selected?: boolean): void => {
    const rowKey = (row as any).id || (row as any).key;
    const index = selectedRowKeys.value.indexOf(rowKey);

    if (selected === undefined) {
      // 切换状态
      if (index > -1) {
        selectedRows.value.splice(selectedRows.value.indexOf(row), 1);
        selectedRowKeys.value.splice(index, 1);
      } else {
        selectedRows.value.push(row);
        selectedRowKeys.value.push(rowKey);
      }
    } else if (selected) {
      // 选中
      if (index === -1) {
        selectedRows.value.push(row);
        selectedRowKeys.value.push(rowKey);
      }
    } else {
      // 取消选中
      if (index > -1) {
        selectedRows.value.splice(selectedRows.value.indexOf(row), 1);
        selectedRowKeys.value.splice(index, 1);
      }
    }
  };

  /**
   * 设置查询参数
   */
  const setQuery = (newQuery: Record<string, any>): void => {
    query.value = { ...newQuery };
  };

  /**
   * 设置分页参数
   */
  const setPagination = (newPagination: Partial<WmsPaginationConfig>): void => {
    pagination.value = { ...pagination.value, ...newPagination };
  };

  // 监听分页变化
  watch(
    () => [pagination.value.page, pagination.value.limit],
    () => {
      if (keepQueryInUrl) {
        updateUrlQuery();
      }
    },
  );

  // 监听查询参数变化
  watch(
    () => query.value,
    () => {
      if (keepQueryInUrl) {
        updateUrlQuery();
      }
    },
    { deep: true },
  );

  /**
   * 更新URL查询参数
   */
  const updateUrlQuery = (): void => {
    if (typeof window === "undefined") return;

    const url = new URL(window.location.href);
    const searchParams = new URLSearchParams();

    // 🔧 安全添加分页参数，确保不为null
    if (pagination.value.page && pagination.value.page > 0) {
    searchParams.set("page", pagination.value.page.toString());
    }
    if (pagination.value.limit && pagination.value.limit > 0) {
    searchParams.set("limit", pagination.value.limit.toString());
    }

    // 🧹 添加查询参数 - 严格过滤null值
    Object.entries(query.value).forEach(([key, value]) => {
      if (value !== null && 
          value !== undefined && 
          value !== "" && 
          value !== "null" &&
          String(value) !== "null") {
        searchParams.set(key, String(value));
        console.log(`[useTable] 📝 设置URL参数: ${key} = ${value}`);
      } else {
        console.warn(`[useTable] ⚠️ 跳过无效URL参数: ${key} = ${value}`);
      }
    });

    // 🔧 安全添加排序参数
    if (sortField.value && 
        sortField.value !== "null" && 
        sortField.value !== "undefined") {
      searchParams.set("sortField", sortField.value);
      
      if (sortOrder.value && 
          (sortOrder.value === "ascending" || sortOrder.value === "descending")) {
        searchParams.set("sortOrder", sortOrder.value);
        console.log(`[useTable] 📝 设置排序参数: ${sortField.value} ${sortOrder.value}`);
      }
    }

    url.search = searchParams.toString();
    window.history.replaceState({}, "", url.toString());
    
    // 🚨 最终检查URL中是否还有null字符串
    if (url.search.includes('null')) {
      console.error(`[useTable] 🚨 警告: URL中仍包含null字符串!`, url.search);
    }
  };

  /**
   * 从URL恢复查询参数
   */
  const restoreFromUrl = (): void => {
    if (typeof window === "undefined") return;

    const url = new URL(window.location.href);
    const searchParams = url.searchParams;

    // 恢复分页参数
    const page = searchParams.get("page");
    const limit = searchParams.get("limit");
    if (page) pagination.value.page = parseInt(page, 10);
    if (limit) pagination.value.limit = parseInt(limit, 10);

    // 恢复查询参数 - 🔧 安全处理URL参数，避免null值
    const restoredQuery: Record<string, any> = {};
    searchParams.forEach((value, key) => {
      if (!["page", "limit", "sortField", "sortOrder"].includes(key)) {
        // 🧹 清理URL参数中的null值和无效值
        if (value && 
            value !== "null" && 
            value !== "undefined" && 
            value !== "" &&
            value.toLowerCase() !== "null") {
          restoredQuery[key] = value;
          console.log(`[useTable] 🔄 恢复URL参数: ${key} = ${value}`);
        } else {
          console.warn(`[useTable] ⚠️ 忽略无效URL参数: ${key} = ${value}`);
        }
      }
    });
    query.value = { ...initialQuery, ...restoredQuery };

    // 恢复排序参数 - 🔧 安全处理排序参数
    const sortFieldValue = searchParams.get("sortField");
    const sortOrderValue = searchParams.get("sortOrder");
    if (sortFieldValue && 
        sortFieldValue !== "null" && 
        sortFieldValue !== "undefined" && 
        sortFieldValue !== "") {
      sortField.value = sortFieldValue;
      
      // 🧹 安全处理排序方向
      if (sortOrderValue && 
          sortOrderValue !== "null" && 
          sortOrderValue !== "undefined" && 
          (sortOrderValue === "ascending" || sortOrderValue === "descending")) {
        sortOrder.value = sortOrderValue as "ascending" | "descending";
        console.log(`[useTable] 🔄 恢复排序: ${sortFieldValue} ${sortOrderValue}`);
      } else {
        sortOrder.value = null;
        console.warn(`[useTable] ⚠️ 无效排序方向，重置为null: ${sortOrderValue}`);
      }
    }
  };

  // 🔧 菜单刷新事件处理
  const route = useRoute();
  let menuRefreshHandler: ((event: CustomEvent) => void) | null = null;

  // 组件挂载时初始化
  onMounted(() => {
    if (keepQueryInUrl) {
      restoreFromUrl();
    }

    if (immediate) {
      loadData();
    }

    // 🎯 监听菜单刷新事件
    menuRefreshHandler = (event: CustomEvent) => {
      const { path } = event.detail;
      console.log(`[useTable] 🔄 接收到菜单刷新事件: ${path}, 当前路由: ${route.path}`);
      
      // 只在当前路由匹配时刷新数据
      if (path === route.path) {
        console.log(`[useTable] 🎯 执行数据刷新`);
        refresh();
      }
    };

    window.addEventListener('menu-refresh', menuRefreshHandler as EventListener);
    console.log(`[useTable] 👂 已注册菜单刷新事件监听器: ${route.path}`);
  });

  // 组件卸载时清理事件监听器
  onBeforeUnmount(() => {
    if (menuRefreshHandler) {
      window.removeEventListener('menu-refresh', menuRefreshHandler as EventListener);
      console.log(`[useTable] 🗑️ 已清理菜单刷新事件监听器: ${route.path}`);
    }
  });

  return {
    // 数据状态
    data,
    tableData: data, // 🔧 添加 tableData 别名以兼容现有组件
    loading,
    isLoading: loading, // 🔧 添加 isLoading 别名以兼容现有组件
    total,

    // 分页状态
    pagination,
    paginationState: pagination, // 🔧 添加 paginationState 别名以兼容现有组件

    // 查询状态
    query,
    searchFilter: query, // 🔧 添加 searchFilter 别名以兼容现有组件

    // 选择状态
    selectedRows,
    selectedRowKeys,

    // 排序状态
    sortField,
    sortOrder,

    // 表格列配置
    columns,
    columnChecks,

    // 方法
    loadData,
    refresh,
    refreshData: refresh, // 🔧 添加 refreshData 别名以兼容现有组件
    search,
    handleSearch: search, // 🔧 添加 handleSearch 别名以兼容现有组件
    resetQuery,
    handleReset: resetQuery, // 🔧 添加 handleReset 别名以兼容现有组件
    handlePageChange,
    onPageSizeChange: handlePageChange, // 🔧 添加 onPageSizeChange 别名以兼容现有组件
    onCurrentPageChange: handlePageChange, // 🔧 添加 onCurrentPageChange 别名以兼容现有组件
    handleSortChange,
    handleSelectionChange,
    clearSelection,
    toggleRowSelection,
    setQuery,
    setPagination,
  };
}

/**
 * 表格列配置Hook
 */
export function useTableColumns<T = any>() {
  const columns = ref<WmsTableColumn<T>[]>([]);

  /**
   * 设置列配置
   */
  const setColumns = (newColumns: WmsTableColumn<T>[]): void => {
    columns.value = newColumns;
  };

  /**
   * 添加列
   */
  const addColumn = (column: WmsTableColumn<T>, index?: number): void => {
    if (index !== undefined) {
      columns.value.splice(index, 0, column);
    } else {
      columns.value.push(column);
    }
  };

  /**
   * 移除列
   */
  const removeColumn = (prop: string): void => {
    const index = columns.value.findIndex((col: WmsTableColumn<T>) => col.prop === prop);
    if (index > -1) {
      columns.value.splice(index, 1);
    }
  };

  /**
   * 更新列配置
   */
  const updateColumn = (
    prop: string,
    updates: Partial<WmsTableColumn<T>>,
  ): void => {
    const column = columns.value.find((col: WmsTableColumn<T>) => col.prop === prop);
    if (column) {
      Object.assign(column, updates);
    }
  };

  /**
   * 显示/隐藏列
   */
  const toggleColumnVisible = (prop: string, visible?: boolean): void => {
    const column = columns.value.find((col: WmsTableColumn<T>) => col.prop === prop);
    if (column) {
      column.visible = visible !== undefined ? visible : !column.visible;
    }
  };

  /**
   * 获取可见列
   */
  const visibleColumns = computed(() => {
    return columns.value.filter((col: WmsTableColumn<T>) => col.visible !== false);
  });

  return {
    columns,
    visibleColumns,
    setColumns,
    addColumn,
    removeColumn,
    updateColumn,
    toggleColumnVisible,
  };
}

/**
 * 表格操作Hook
 */
export function useTableActions<T = any>() {
  /**
   * 批量删除确认
   */
  const confirmBatchDelete = async (
    selectedRows: T[],
    deleteApi: (ids: any[]) => Promise<void>,
    options: {
      title?: string;
      message?: string;
      getRowId?: (row: T) => any;
    } = {},
  ): Promise<boolean> => {
    const {
      title = "确认删除",
      message = `确定要删除选中的 ${selectedRows.length} 条记录吗？`,
      getRowId = (row: any) => row.id,
    } = options;

    if (selectedRows.length === 0) {
      ElMessage.warning("请选择要删除的记录");
      return false;
    }

    try {
      await ElMessageBox.confirm(message, title, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });

      const ids = selectedRows.map(getRowId);
      await deleteApi(ids);

      ElMessage.success("删除成功");
      return true;
    } catch (error) {
      if (error !== "cancel") {
        console.error("删除失败:", error);
        ElMessage.error("删除失败");
      }
      return false;
    }
  };

  /**
   * 单行删除确认
   */
  const confirmSingleDelete = async (
    row: T,
    deleteApi: (id: any) => Promise<void>,
    options: {
      title?: string;
      message?: string;
      getRowId?: (row: T) => any;
    } = {},
  ): Promise<boolean> => {
    const {
      title = "确认删除",
      message = "确定要删除这条记录吗？",
      getRowId = (row: any) => row.id,
    } = options;

    try {
      await ElMessageBox.confirm(message, title, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });

      const id = getRowId(row);
      await deleteApi(id);

      ElMessage.success("删除成功");
      return true;
    } catch (error) {
      if (error !== "cancel") {
        console.error("删除失败:", error);
        ElMessage.error("删除失败");
      }
      return false;
    }
  };

  /**
   * 导出数据
   */
  const exportData = async (
    exportApi: (params: any) => Promise<Blob>,
    query: Record<string, any>,
    filename?: string,
  ): Promise<void> => {
    try {
      const blob = await exportApi(query);

      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = filename || `export_${Date.now()}.xlsx`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      ElMessage.success("导出成功");
    } catch (error) {
      console.error("导出失败:", error);
      ElMessage.error("导出失败");
    }
  };

  return {
    confirmBatchDelete,
    confirmSingleDelete,
    exportData,
  };
}

// 导出类型接口
export type { UseTableOptions, UseTableReturn };
